package com.woniuxy.user.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author: Mr·Xiang
 * @create 2024-04-07 9:37
 */

@Data
public class User implements UserDetails, Serializable {
    private static final long serialVersionUID = 1L;
    private Integer id;
    private String uname;
    @JsonIgnore  // 在对象与JSON互转时忽略该属性
    private String password;

    private String phone;
    private String name;

    private String lockstate;

    // setter方法
    public void setCellphone(String cellphone){
        String regex = "(\\d{3})\\d{4}(\\d{4})";
        String replacement = "$1****$2";
        this.phone = cellphone.replaceAll(regex, replacement);
    }
    private List<Role> roleList;

    // 获取当前用户的所有角色、权限信息
    // 泛型上界：<? extends xxx>   <>中的类型必须是xxx的类型及其子类型
    // 泛型下界：<? super xxx>     <>中的类型必须是xxx类及其父类
    @JsonIgnore
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        // 遍历用户的角色、权限信息封装成SimpleGrantedAuthority对象
        roleList.forEach(role -> {
            // 封装用户的角色信息
            authorities.add(new SimpleGrantedAuthority(role.getName()));
            // 遍历权限
            role.getPermsList().forEach(perms -> {
                authorities.add(new SimpleGrantedAuthority(perms.getName()));
            });
        });
        return authorities;
    }

    // 获取用户名
    @Override
    public String getUsername() {
        return uname;
    }

    // 账号是否没有过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    // 账号是否没有被锁定
    @Override
    public boolean isAccountNonLocked() {
        if ("0".equals(lockstate)){
            return false;
        }
        return true;
    }

    // 账号的认证信息是否没有过期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    // 账号是否可用
    @Override
    public boolean isEnabled() {
        return true;
    }
}
